#!/usr/bin/bash

# Copyright (c) 2023. Huawei Technologies Co.,Ltd.ALL rights reserved.
# This program is licensed under Mulan PSL v2.
# You can use it according to the terms and conditions of the Mulan PSL v2.
#          http://license.coscl.org.cn/MulanPSL2
# THIS PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.

# #############################################
# @Author    :   lufei
# @Contact   :   lufei@uniontech.com
# @Date      :   2024/08/21
# @License   :   Mulan PSL v2
# @Desc      :   Test gnu as
# ############################################

source "${OET_PATH}"/libs/locallibs/common_lib.sh

function pre_test() {
    LOG_INFO "Start to prepare the test environment."
    DNF_INSTALL "binutils"
    if [ "$NODE1_FRAME" == "riscv64" ]; then
        cat >hello.s <<EOF
        .section .text
        .globl _start

_start:
        # write(fd=1, buf=message, count=13)
        li      a7, 64           # syscall number for write
        li      a0, 1            # stdout
        la      a1, message      # buffer
        li      a2, 13           # length
        ecall

        # exit(code=0)
        li      a7, 93           # syscall number for exit
        li      a0, 0
        ecall

        .section .data
message:
        .ascii "Hello, world\\n"
EOF
    elif [ "$NODE1_FRAME" == "aarch64" ]; then
        cat >hello.s <<EOF
        .global _start

        .text
_start:
        # write(1, message, 13)
        mov     x8, #64
        mov     x0, #1
        ldr     x1, =message
        mov     x2, #13
        svc     #0

        # exit(0)
        mov     x8, #93
        mov     x0, #0
        svc     #0
message:
        .ascii  "Hello, world\n"
EOF
    else
        cat >hello.s <<EOF
        .global _start

        .text
_start:
        # write(1, message, 13)
        mov     \$1, %rax
        mov     \$1, %rdi
        mov     \$message, %rsi
        mov     \$13, %rdx
        syscall

        # exit(0)
        mov     \$60, %rax
        xor     %rdi, %rdi
        syscall
message:
        .ascii  "Hello, world\n"
EOF
    fi
    LOG_INFO "End to prepare the test environment."
}

function run_test() {
    LOG_INFO "Start to run test."
    as hello.s -o hello.o
    CHECK_RESULT $? 0 0 "assemble failed." 1
    ld hello.o -o hello
    CHECK_RESULT $? 0 0 "link failed." 1
    ./hello | grep "Hello, world"
    CHECK_RESULT $? 0 0 "./hello execution run failed."
    LOG_INFO "End to run test."
}

function post_test() {
    LOG_INFO "Start to restore the test environment."
    DNF_REMOVE "$@"
    rm -rf hello.s hello.o hello
    LOG_INFO "End to restore the test environment."
}

main "$@"
